// 微信小程序 登录
const createConfig = require('uni-config-center');

async function code2session(mpConfig, code, $dx) {
	// https://api.weixin.qq.com/sns/jscode2session
	const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${mpConfig.appid}&secret=${mpConfig.appsecret}&js_code=${code}&grant_type=authorization_code`;
	const http = new $dx.Curl();
	const res = await http.get(url);
	if (res.errcode) {
		$dx.error(res.errmsg);
	}
	return res;
}

module.exports = {
	// 登陆
	async login() {
		const code = this.$dx.request.post('code');
		const nickname = this.$dx.request.post('nickname');
		const avatar = this.$dx.request.post('avatar');
		if (!code) {
			this.$dx.error('code 不能为空');
		}
		const uniIdConfig = createConfig({
			pluginId: 'uni-id', // 插件id
			// defaultConfig: {},
			customMerge: function (defaultConfig, userConfig) {
				return Object.assign(defaultConfig, userConfig);
			},
		});
		const config = uniIdConfig.config('mp-weixin.oauth');
		const dCloudAppid = this.$dx.request.appId;
		if (!dCloudAppid) {
			this.$dx.error('未获取到 dCloud Appid');
		}
		if (!config || !config[dCloudAppid] || !config[dCloudAppid].appid) {
			this.$dx.error('未配置小程序 Appid');
		}
		const mpConfig = config[dCloudAppid];
		const res = await code2session(mpConfig, code, this.$dx);
		const dcloud_appid = this.$dx.request.appId;
		let user;
		if (res.unionid) {
			user = await this.$dx.service.user.where('wx_unionid', res.unionid).find();
			// 判断和更新用户信息
			// 其他凭他的openid 更新到当前用户
			if (user && (!user.wx_openid || user.wx_openid.mp !== res.openid)) {
				await this.$dx.service.user.save({
					_id: user._id,
					wx_openid: {
						mp: res.openid,
					},
					third_party: {
						mp_weixin: {
							session_key: res.session_key,
						},
					},
				});
			}
		}
		if (!user) {
			user = await this.$dx.service.user.where('wx_openid.mp', res.openid).find();
		}
		// 找到了
		if (user) {
			// 用户已禁用
			if (user.status !== 0) {
				this.$dx.error('用户已禁用');
			}
			// 判断是否有应用权限
			if (user.dcloud_appid.length && !user.dcloud_appid.includes(dcloud_appid)) {
				await this.$dx.service.logs.addLoginLog(user._id, user.username, 'login', 0, user.mobile, user.email);
				this.$dx.error('账号没有应用权限');
			}
			// 登录
			return await this.$dx.service.user.loginByUser(user);
		}
		// 没找到
		user = {
			wx_openid: {
				mp: res.openid,
			},
			third_party: {
				mp_weixin: {
					session_key: res.session_key,
				},
			},
		};
		if (res.unionid) {
			user.wx_unionid = res.unionid;
		}
		if (nickname) {
			user.nickname = nickname;
		} else {
			user.nickname = '微信用户' + res.openid.substr(0, 4) + '****' + res.openid.substr(-4);
		}
		if (avatar) {
			user.avatar = avatar;
		}
		const time = Date.now();
		const ip = this.$dx.request.ip;
		user.username = res.openid;
		user.role = [];
		user.register_date = time;
		user.register_ip = ip;
		user.last_login_ip = ip;
		user.last_login_date = time;
		user.status = 0;
		user.dcloud_appid = [dcloud_appid];
		user.mobile = '';
		user.email = '';
		user.money = 0;
		user.score = 0;
		// 注册
		let uid = await this.$dx.service.user.insert(user);
		user._id = uid;
		return await this.$dx.service.user.loginByUser(user);
	},
};
